package com.google.code.UtopiaXml;

/**
 * Class representing an xs:sequence with maxOccurs>1. It will generate a
 * separate class.
 *
 * @author Michael Simacek
 */
public class MultiSequence extends MultiIndicator {

    /**
     * Creates empty sequence.
     *
     * @param name
     */
    public MultiSequence(String name) {
        super(name);
    }

    @Override
    public void generateParserBlock(CodeBuilder cb, String parentObject, String nodeName) {
        cb.appendLine("//begin MultiSequence");
        String listName = nodeName + "List";
        cb.appendLine("List <" + getName() + "> " + listName + " = new ArrayList<" + getName() + ">();");
        cb.addImport("java.util.List");
        cb.addImport("java.util.ArrayList");

        cb.appendLine("do {");
        String resName = nodeName + "Sequence";

        cb.appendLine(getName() + " " + resName + " = new " + getName() + "();");

        for (IndicatorContent item : getContent()) {
            StringBuilder cond = new StringBuilder("if (" + nodeName + " != null && (");
            for (String match : item.getMatchStrings()) {
                cond.append("\"").append(match).append("\"").append(".equals(").
                        append(nodeName).append(".getNodeName()) || ");
            }
            if (cond.length() > 3) {
                cond.setLength(cond.length() - 4);
            }
            cond.append(")) {");
            cb.appendLine(cond.toString());
            item.generateParserBlock(cb, resName, nodeName);
            cb.appendLine("}");
        }

        cb.appendLine(listName + ".add(" + resName + ");");

        StringBuilder cond = new StringBuilder(nodeName + " != null && (");
        for (String match : getMatchStrings()) {
            cond.append("\"").append(match).append("\"").append(".equals(").append(nodeName).append(".getNodeName()) || ");
        }
        if (cond.length() > 3) {
            cond.setLength(cond.length() - 4);
        }
        cond.append(")");
        cb.appendLine("} while (" + cond + ");");

        cb.appendLine(parentObject + ".set" + CodeBuilder.toUpperCamelCase(getName()) + "(" + listName + ");");
        cb.appendLine("//end MultiSequence");
    }

    @Override
    protected Indicator shallowCopy() {
        return new MultiSequence(getName());
    }
}
